package com.example.demo.service.impl;

import com.example.demo.mapper.TeacherApprovalMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.TeacherApproval;
import com.example.demo.model.User;
import com.example.demo.model.Role;
import com.example.demo.service.TeacherApprovalService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 教师权限申请审批服务实现类
 */
@Service
public class TeacherApprovalServiceImpl implements TeacherApprovalService {

    @Autowired
    private TeacherApprovalMapper teacherApprovalMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    @Transactional
    public TeacherApproval createApproval(Integer userId, String requestedRole, String approvalComment) {
        // 检查用户是否存在
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查用户是否为教师
        if (!"TEACHER".equals(user.getUserType())) {
            throw new RuntimeException("只有教师可以申请管理员权限");
        }
        
        // 检查是否已有未处理的相同申请
        if (hasPendingApproval(userId, requestedRole)) {
            throw new RuntimeException("已有相同权限的待处理申请");
        }
        
        // 创建申请
        TeacherApproval approval = new TeacherApproval();
        approval.setUserId(userId);
        approval.setRequestedRole(requestedRole);
        approval.setApprovalStatus("PENDING");
        approval.setApprovalComment(approvalComment);
        
        teacherApprovalMapper.insert(approval);
        
        return approval;
    }
    
    @Override
    @Transactional
    public TeacherApproval approveRequest(Integer approvalId, Integer approverId, boolean isApproved, String comment) {
        // 检查申请是否存在
        TeacherApproval approval = teacherApprovalMapper.findById(approvalId);
        if (approval == null) {
            throw new RuntimeException("申请不存在");
        }
        
        // 检查申请状态
        if (!"PENDING".equals(approval.getApprovalStatus())) {
            throw new RuntimeException("该申请已被处理");
        }
        
        // 检查审批者是否存在
        User approver = userMapper.findById(approverId);
        if (approver == null) {
            throw new RuntimeException("审批者不存在");
        }
        
        // 检查审批者权限
        if (!canApprove(approverId, approval.getRequestedRole())) {
            throw new RuntimeException("没有足够的权限进行审批");
        }
        
        // 更新申请状态
        approval.setApprovalStatus(isApproved ? "APPROVED" : "REJECTED");
        approval.setApproverId(approverId);
        approval.setApprovalComment(comment);
        
        teacherApprovalMapper.update(approval);
        
        // 获取被审批的用户
        User user = userMapper.findById(approval.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        try {
            JSONObject extraInfo = user.getExtraInfo() != null && !user.getExtraInfo().isEmpty() ?
                    new JSONObject(user.getExtraInfo()) : new JSONObject();
            
            if (isApproved) {
                // 如果是管理员角色申请，同时也通过教师账号审批
                if (!"TEACHER".equals(approval.getRequestedRole())) {
                    // 更新管理员角色信息
                    extraInfo.put("admin_role", approval.getRequestedRole());
                    extraInfo.put("admin_role_status", "1");
                    extraInfo.put("admin_role_comment", comment);
                    // 同时通过教师账号审批
                    extraInfo.put("approval_status", "1");
                    extraInfo.put("approval_comment", "教师账号审核已通过");
                    System.out.println("管理员角色和教师账号同时审批通过 - " +
                                     "用户ID: " + user.getUserId() + 
                                     ", 管理员角色: " + approval.getRequestedRole());
                } else {
                    // 如果只是教师账号申请
                    extraInfo.put("approval_status", "1");
                    extraInfo.put("approval_comment", "教师账号审核已通过");
                    System.out.println("教师账号审批通过 - 用户ID: " + user.getUserId());
                }
            } else {
                // 如果是拒绝管理员角色申请
                if (!"TEACHER".equals(approval.getRequestedRole())) {
                    extraInfo.put("admin_role_status", "2");
                    extraInfo.put("admin_role_comment", comment);
                    // 移除被拒绝的管理员角色
                    extraInfo.remove("admin_role");
                    System.out.println("管理员角色申请被拒绝 - 用户ID: " + user.getUserId());
                } else {
                    // 如果是拒绝教师账号申请
                    extraInfo.put("approval_status", "2");
                    extraInfo.put("approval_comment", comment);
                    System.out.println("教师账号申请被拒绝 - 用户ID: " + user.getUserId());
                }
            }
            
            // 更新用户信息
            user.setExtraInfo(extraInfo.toString());
            int updateResult = userMapper.update(user);
            
            if (updateResult != 1) {
                throw new RuntimeException("更新用户状态失败");
            }
            
            System.out.println("用户状态更新完成 - " +
                             "用户ID: " + user.getUserId() + 
                             ", 用户码: " + user.getUsercode() +
                             ", 申请角色: " + approval.getRequestedRole() +
                             ", 是否通过: " + isApproved +
                             ", 新的extraInfo: " + user.getExtraInfo());
            
        } catch (Exception e) {
            throw new RuntimeException("更新用户状态失败：" + e.getMessage());
        }
        
        return approval;
    }
    
    @Override
    public TeacherApproval findById(Integer approvalId) {
        return teacherApprovalMapper.findById(approvalId);
    }
    
    @Override
    public List<TeacherApproval> findByUserId(Integer userId) {
        return teacherApprovalMapper.findByUserId(userId);
    }
    
    @Override
    public List<TeacherApproval> findByStatus(String status) {
        return teacherApprovalMapper.findByStatus(status);
    }
    
    @Override
    public List<TeacherApproval> findAll() {
        return teacherApprovalMapper.findAll();
    }
    
    @Override
    public boolean canApprove(Integer approverId, String requestedRole) {
        User approver = userMapper.findById(approverId);
        if (approver == null) {
            return false;
        }
        
        // 超级管理员可以审批所有申请
        if ("SUPER_ADMIN".equals(approver.getUserType())) {
            return true;
        }
        
        // 教师只有在具有管理员角色且权限级别更高时才能审批
        if ("TEACHER".equals(approver.getUserType())) {
            try {
                JSONObject extraInfo = new JSONObject(approver.getExtraInfo());
                String adminRole = extraInfo.optString("admin_role", "");
                String adminRoleStatus = extraInfo.optString("admin_role_status", "0");
                
                // 检查管理员角色是否已审核通过
                if (!"1".equals(adminRoleStatus)) {
                    return false;
                }
                
                // 班级管理员不能审批任何角色
                if ("CLASS_ADMIN".equals(adminRole)) {
                    return false;
                }
                
                // 检查权限级别
                return !adminRole.isEmpty() && Role.getPrivilegeLevel(adminRole) > Role.getPrivilegeLevel(requestedRole);
            } catch (Exception e) {
                return false;
            }
        }
        
        return false;
    }
    
    @Override
    public boolean hasPendingApproval(Integer userId, String requestedRole) {
        return teacherApprovalMapper.findPendingApproval(userId, requestedRole) != null;
    }
} 